import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mathfun/components/stat_card.dart';
import '../features/training_records/bloc/training_history_bloc.dart';
import '../features/training_records/bloc/training_history_event.dart';
import '../features/training_records/model/training_record.dart';

class DotFlashTrainingResultPage extends StatefulWidget {
  final int totalQuestions;
  final int correctCount;
  final List<int> responseTimes;
  final List<bool> correctness;

  const DotFlashTrainingResultPage({
    super.key,
    required this.totalQuestions,
    required this.correctCount,
    required this.responseTimes,
    required this.correctness,
  });

  @override
  State<DotFlashTrainingResultPage> createState() => _DotFlashTrainingResultPageState();
}

class _DotFlashTrainingResultPageState extends State<DotFlashTrainingResultPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _autoSaveTrainingRecord());
  }

  void _autoSaveTrainingRecord() {
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);
    final record = TrainingRecord(
      type: 'dot_flash',
      correctCount: widget.correctCount,
      totalCount: widget.totalQuestions,
      durationMs: duration,
      timestamp: DateTime.now(),
    );
    context.read<TrainingHistoryBloc>().add(TrainingRecordAdded(record));
  }

  @override
  Widget build(BuildContext context) {
    final accuracy = widget.totalQuestions > 0 ? (widget.correctCount / widget.totalQuestions * 100) : 0;
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);
    final minutes = duration ~/ 60000;
    final seconds = (duration % 60000) ~/ 1000;
    final avgResponseTime = widget.responseTimes.isNotEmpty
        ? (widget.responseTimes.reduce((a, b) => a + b) / widget.responseTimes.length).toStringAsFixed(0)
        : '0';

    return Scaffold(
      appBar: AppBar(
  title: const Text('数点快闪训练结果'),
  leading: IconButton(
    icon: const Icon(Icons.arrow_back),
    onPressed: () => Navigator.popUntil(context, (route) => route.isFirst),
  ),
),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              const SizedBox(height: 16),
              // 由于 _buildResultIndicator 方法未定义，这里暂时注释掉该调用
              // _buildResultIndicator(accuracy.toDouble()),
              // 可以根据实际需求实现该方法后再取消注释
              const SizedBox(height: 16),
              _buildStatsGrid(minutes, seconds, avgResponseTime),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: () => Navigator.popUntil(context, (route) => route.isFirst),
                icon: const Icon(Icons.check_circle),
                label: const Text('记录已自动保存，返回首页'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  textStyle: const TextStyle(fontSize: 16),
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatsGrid(int minutes, int seconds, String avgResponseTime) {
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 2,
      crossAxisSpacing: 8,
      mainAxisSpacing: 8,
      childAspectRatio: 1.333,
      children: [
        StatCard(
          icon: Icons.check,
          title: '正确题数',
          value: '${widget.correctCount}/${widget.totalQuestions}',
        ),
        StatCard(
          icon: Icons.timer,
          title: '用时',
          value: '${minutes}分${seconds}秒',
        ),
        StatCard(
          icon: Icons.trending_up,
          title: '正确率',
          value: '${(widget.correctCount/widget.totalQuestions*100).toStringAsFixed(1)}%',
        ),
        StatCard(
          icon: Icons.insights,
          title: '平均反应',
          value: '${avgResponseTime}ms',
        ),
      ],
    );
  }
}